package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * AxdrFloat32类
 * 实现32位浮点数数据的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class AxdrFloat32 implements AxdrType {
    private float value = 0.0f;
    private byte[] dataCode = null;

    public AxdrFloat32() {
    }

    public AxdrFloat32(float value) {
        this.value = value;
    }

    public float getValue() {
        return value;
    }

    public void setValue(float value) {
        this.value = value;
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        // 解码4个字节的浮点数（大端序）
        int b1 = input.read() & 0xFF;
        int b2 = input.read() & 0xFF;
        int b3 = input.read() & 0xFF;
        int b4 = input.read() & 0xFF;
        int intValue = (b1 << 24) | (b2 << 16) | (b3 << 8) | b4;
        this.value = Float.intBitsToFloat(intValue);
        return 4;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        // 编码4个字节的浮点数（大端序）
        int intValue = Float.floatToIntBits(this.value);
        try {
            output.write((intValue >> 24) & 0xFF);
            output.write((intValue >> 16) & 0xFF);
            output.write((intValue >> 8) & 0xFF);
            output.write(intValue & 0xFF);
        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        }
        return 4;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        return String.valueOf(this.value);
    }
}